package run.microservice.stock.config;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import run.microservice.stock.listener.BaseInsertListener;
import run.microservice.stock.listener.BaseUpdateListener;
import run.microservice.stock.model.entity.BaseEntity;

/**
 * @author lunfy
 * @description:
 * @date 2024-04-22 16:22
 */
@Configuration
public class CustomizerFlexGlobalConfig implements MyBatisFlexCustomizer {

    private static final Logger log = LoggerFactory.getLogger("mybatis-flex-full-sql");

    @Override
    public void customize(FlexGlobalConfig flexGlobalConfig) {
        BaseInsertListener insertListener = new BaseInsertListener();
        BaseUpdateListener updateListener = new BaseUpdateListener();
        flexGlobalConfig.registerInsertListener(insertListener, BaseEntity.class);
        flexGlobalConfig.registerUpdateListener(updateListener, BaseEntity.class);

        // 启用完整SQL打印
        this.enableFullSqlPrint();
    }

    /**
     * 启用完整SQL打印
     */
    private void enableFullSqlPrint() {
        //开启审计功能
        AuditManager.setAuditEnable(true);

        //设置 SQL 审计收集器
        AuditManager.setMessageCollector(auditMessage -> {

            log.info("\n===>  SQL：{}\n===>  耗时：{}ms", auditMessage.getFullSql(), auditMessage.getElapsedTime());
        });
    }
}
